var fs = require('fs');
//readfile
fs.readFile('ioredis.js',function(err,data){
    if(err){
        return console.error(err);
    }
    else{
        console.log("异步读取："+data.toString());

    }
});
//writefile
fs.writeFile('input.txt',"写入的内容",function(err){
    if(err){
        return console.error(err);
    }else{
        console.log('写入成功');
    }
});
var buf = Buffer.alloc(1024);
 
//open txt
console.log("准备打开文件！");
fs.open('at.txt', 'r+', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
   if (err){
     console.log(err);
   }
   // 仅输出读取的字节
   if(bytes > 0){
     console.log(buf.slice(0, bytes).toString());
   }
  });
});
//数据查看状态
fs.stat('input.txt', function (err, stats) {
    console.log(stats.isFile());     //true
    console.log(stats.isDirectory());     //true
  });


//创建读取流
var data='';
var readerStream=fs.createReadStream('input.txt');
readerStream.setEncoding('UTF8');
readerStream.on('data',function(chunk){
    data +=chunk;
    console.log(data);
});
readerStream.on('end',function(){
    console.log(data);
  });
  readerStream.on('error', function(err){
    console.log(err.stack);
  }); 

//创建写入流
var datawrite="写入流的数据";
var writeStream=fs.createWriteStream('output2.txt');
writeStream.write(datawrite,'UTF8');
writeStream.end();

writeStream.on('finish',function(){
    console.log('写入完成');
});
writeStream.on('error',function(err){
    console.log(err.stack);
});


//创建管道流
var reader=fs.createReadStream('input.txt');
var writer=fs.createWriteStream('out.txt');
//通过管道将读取的流传入到写入流中
reader.pipe(writer);

//链式流
var zlib=require('zlib');
//压缩文件
fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));
console.log("文件压缩完成。");

fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("文件解压完成。");